#include "JGLVideo.h"
#include "JGLWidget.h"
#include "JLog.h"

JGLVideo::JGLVideo(const JGLWidget* viewer,
				   LPCTSTR lpszOutputMovieFileName, 
				   int nFrameWidth,
				   int nFrameHeight,
				   DWORD dwFrameRate,
				   int nBitsPerPixel,
				   DWORD dwCodec )
				   : m_MovieFile(lpszOutputMovieFileName, dwCodec, dwFrameRate),
				   m_bRecord(true)
{
	m_nWidth = nFrameWidth;
	m_nHeight = nFrameHeight;
	m_nBitsPerPixel = nBitsPerPixel;

	m_pBits = malloc(m_nWidth * m_nHeight * m_nBitsPerPixel/8);	/*create the required memory to hold the frame content*/
	connect(viewer, SIGNAL(drawNeeded()), this, SLOT(draw()));
}

JGLVideo::~JGLVideo()
{
	if(m_pBits)
	{
		free(m_pBits);
		m_pBits = NULL;
	}
}

void JGLVideo::draw()
{

	const float nbSteps = 200.0;
	glBegin(GL_QUAD_STRIP);
	for (int i=0; i<nbSteps; ++i)
	{
		const float ratio = i/nbSteps;
		const float angle = 21.0*ratio;
		const float c = cos(angle);
		const float s = sin(angle);
		const float r1 = 1.0 - 0.8f*ratio;
		const float r2 = 0.8f - 0.8f*ratio;
		const float alt = ratio - 0.5f;
		const float nor = 0.5f;
		const float up = sqrt(1.0-nor*nor);
		glColor3f(1.0-ratio, 0.2f , ratio);
		glNormal3f(nor*c, up, nor*s);
		glVertex3f(r1*c, alt, r1*s);
		glVertex3f(r2*c, alt+0.05f, r2*s);
	}
	glEnd();
	
	if(m_bRecord)
	{
		glFlush();
		glFinish();
		glReadPixels(0, 0, m_nWidth, m_nHeight, GL_BGR_EXT, GL_UNSIGNED_BYTE, m_pBits);
		m_MovieFile.AppendNewFrame(m_nWidth, m_nHeight, m_pBits, m_nBitsPerPixel);
	}
}